//画笔颜色调整, 居民区样式丢失, 裁剪区域合并
let drawLine = null
const resultBaseUrl = 'gdbp://MapGisLocal/wuhan/sfcls/'
let resultname = null
const affectedArea = []
const announcePageSize = 5
let resultClipLayer

//点击触发 开始/结束 发布公告事件
function handleAnnounceClick() {
  if (drawCircle) {
    map.removeInteraction(drawCircle)
  }
  // if (drawLine) {
  //   drawLine = null
  //   source.clear()
  //   map.removeInteraction(drawLine)
  //   map.removeLayer(resultClipLayer)
  //   map.on('click', addPopup)
  //   return
  // }
  map.un('click', addPopup)
  drawLine = createDraw(source, 'LineString', announceDrawend)
  map.addInteraction(drawLine)
}
//交互式绘制结束的回调
function announceDrawend(e) {
  const points = e.feature.getGeometry().getCoordinates()
  //将绘制的多边形每个点坐标转换成mapgis点对象, 并存入arc_points数组
  //每次绘制结束, arc_points存储的都是最新的几何对象的信息

  const arc_points = points.map((item) => {
    return new Zondy.Object.Point2D(item[0], item[1])
  })
  //console.log(arc_points)
  singleBuffAnalysis(0.001, arc_points)
}

//缓冲分析
function singleBuffAnalysis(radius, arc_points) {
  const gArc = new Zondy.Object.Arc(arc_points)
  //构成线的折线
  const gAnyLine = new Zondy.Object.AnyLine([gArc])
  //设置线要素的几何信息
  const gline = new Zondy.Object.GLine(gAnyLine)
  //设置要素的几何信息
  const fGeom = new Zondy.Object.FeatureGeometry({ LinGeom: [gline] })

  //设置属性结构
  const regAttStr = new Zondy.Object.CAttStruct({
    FldName: ['ID', '周长', 'LayerID'],
    FldNumber: 3,
    FldType: ['FldLong', 'FldDouble', 'FldLong'],
  })
  const values = [1, 0.132101984752282, 8]
  //实例化CAttDataRow类
  const valuesRow = new Zondy.Object.CAttDataRow(values, 1)

  //实例化FeatureBuffBySingleRing类，设置要素缓冲分析必要参数，输出分析结果到缓冲分析结果图层
  const featureBufBySR = new Zondy.Service.FeatureBuffBySingleRing({
    ip: 'localhost',
    port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089,
    //设置要素缓冲分析左半径
    leftRad: radius,
    //设置要素缓冲分析右半径
    rightRad: radius,
  })

  resultname = resultBaseUrl + 'roadsBuffer' + Date.now()

  /*设置缓冲分析参数*/
  //设置几何信息
  featureBufBySR.sfGeometryXML = JSON.stringify([fGeom])
  //设置属性结构
  featureBufBySR.attStrctXML = JSON.stringify(regAttStr)
  //设置属性值
  featureBufBySR.attRowsXML = JSON.stringify([valuesRow])
  //设置追踪半径
  featureBufBySR.traceRadius = 0.0001
  //设置缓冲结果的名称以及存放地址
  featureBufBySR.resultName = resultname

  //调用Zondy.Service.AnalysisBase基类的execute方法执行要素缓冲分析，AnalysisSuccess为回调函数。
  featureBufBySR.execute(bufferAnalysisSuccess, 'post', false, 'json')
}

//缓冲分析成功的回调--裁剪分析
function bufferAnalysisSuccess(data) {
  map.removeInteraction(drawLine)
  if (data.succeed) {
    const clspath = data.results[0].Value
    resultname = resultBaseUrl + 'roadsClip' + Date.now()
    //实例化ClipByLayer类
    const clipParam = new Zondy.Service.ClipByLayer({
      ip: 'localhost',
      port: '6163',
      //源简单要素类的URL
      srcInfo1: 'gdbp://MapGisLocal/wuhan/sfcls/居民区',
      //裁剪框简单要素类的URL
      srcInfo2: clspath,
      //设置结果URL
      desInfo: resultname,
      infoOptType: 0,
    })
    //调用基类的execute方法，执行图层裁剪分析。AnalysisSuccess为结果回调函数
    clipParam.execute(clipSuccess, 'post', false, 'json', clipError)
  } else {
    alert('缓冲区分析失败，请检查参数！')
  }
}

//裁剪成功的回调
function clipSuccess(data) {
  //console.log(data)
  map.removeLayer(resultClipLayer)
  if (data.succeed) {
    //将结果图层添加到地图视图中显示
    resultClipLayer = new Zondy.Map.GdbpLayer('resultClipLayer', [resultname], {
      ip: 'localhost',
      port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089,
      //isBaseLayer: false,
      //解决导出图片, 画布污染问题
      crossOrigin: 'Anonymous',
    })
    map.addLayer(resultClipLayer)
    queryByAttribute(resultname)
  } else {
    alert('叠加分析失败，请检查参数！')
  }
}

function clipError(e) {
  console.log(e)
}

//通过gdbp查询要素图层
function queryByAttribute(gdbpUrl) {
  //初始化查询结构对象，设置查询结构包含几何信息
  const queryStruct = new Zondy.Service.QueryFeatureStruct()
  queryStruct.IncludeGeometry = true
  //实例化查询参数对象
  const queryParam = new Zondy.Service.QueryByLayerParameter(gdbpUrl, {
    resultFormat: 'json',
    struct: queryStruct,
  })
  queryParam.where = '1>0'
  //实例化地图文档查询服务对象
  const queryService = new Zondy.Service.QueryLayerFeature(queryParam, {
    ip: 'localhost',
    port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089
  })
  //执行查询操作，querySuccess为查询回调函数
  queryService.query(queryAnnounceSuccess)
}

//查询成功回调
function queryAnnounceSuccess(result) {
  //console.log(result)
  if (!result.SFEleArray.length) {
    alert('没有受影响的居民区')
    source.clear()
    drawLine = null
    map.removeLayer(resultClipLayer)
    map.on('click', addPopup)
    return
  }
  //显示发布公告容器
  $('#footer-announce').removeClass('hide')
  //清除表格数据
  $('#announce-table tr:not(:first)').html('')
  //清除分页器的li节点
  $('#announce-pagination').empty()
  //清除数组数据
  affectedArea.splice(0, affectedArea.length)

  const result1 = removeDuplicate(result.SFEleArray)
  //将受影响的区域名称和物业电话显示出来(前五条)
  result1.forEach((element) => {
    if (result1.indexOf(element) < announcePageSize) {
      const list = `
      <tr>
      <td>${element.AttValue[4]}</td>
      <td>${element.AttValue[5]}</td>
    </tr>
    `
      $('#announce-table').append(list)
    }
    affectedArea.push({ region: element.AttValue[4], tel: element.AttValue[5] })
  })
  //console.log(affectedArea)
  //设置条目数
  $('#announce-total').text(`共${result1.length}条`)
  //设置分页器的个数
  for (let i = 0; i < result1.length / announcePageSize; i++) {
    $('#announce-pagination').append(
      `<li><a href="#" onclick="toggleAnnounceTable(${
        i + 1
      },affectedArea,event)">${i + 1}</a></li>`
    )
  }
  //默认分页1处于激活
  $('#announce-pagination').children(':first').addClass('active')
}

//公告分页器
function toggleAnnounceTable(page, data, event) {
  //清除数据
  $('#announce-table').children().not(':first').remove()
  //计算偏移量
  const offset = (page - 1) * announcePageSize
  for (let i = offset; i < offset + announcePageSize; i++) {
    //数据为空时,跳出循环体
    if (!data[i]) {
      break
    }
    const list = `
      <tr>
      <td>${data[i].region}</td>
      <td>${data[i].tel}</td>
    </tr>
    `
    $('#announce-table').append(list)
  }
  $(event.target).parent().addClass('active')
  $(event.target).parent().siblings().removeClass('active')
}

//提交, 发布公告
function submitAnnounce() {
  //数据
  const region = affectedArea.map((item) => {
    return item.region
  })
  console.log($('#annouce-message').val())
  const data = {
    user_id: user_id,
    notice_content: $('#annouce-message').val(),
    affected_area: '"' + region + '"',
  }
  console.log(data)
  //发送添加请求, 将公告存入gg_notice
  $.ajax({
    url: BaseURL + '/traffic/gg_notice',
    type: 'POST',
    dataType: 'json',
    data: data,
    success: function (res) {
      if (res.code == 1) {
        alert('发布公告成功')
      }
    },
  })
}

//删除裁剪分析后重复的要素(裁剪分析要素合并问题)
function removeDuplicate(arr) {
  let len = arr.length
  for (let i = 0; i < len; i++) {
    for (let j = i + 1; j < len; j++) {
      if (arr[i].AttValue[4] === arr[j].AttValue[4]) {
        arr.splice(j, 1) //数组删除的方法, 改变了数组本身
        len-- // 减少循环次数提高性能
        j-- // 保证j的值自加后不变
      }
    }
  }
  return arr
}

//查看公告
function viewAnnouncement() {
  $('#viewAnnounce-table').empty()
  //发送查询请求, 获取gg_notice最新公告
  $.ajax({
    url: BaseURL + '/user/gg_notice',
    type: 'GET',
    dataType: 'json',
    success: function (res) {
      if (res.code == 1) {
        console.log(res.result)
        const tr = `
        <tr>
          <td>发布时间</td>
          <td>${res.result[0].notice_time}</td>
        </tr>
        <tr>
          <td>影响区域</td>
          <td>${res.result[0].affected_area.replace(/"/g, '')}</td>
        </tr>
        <tr>
          <td>公告内容</td>
          <td>${res.result[0].notice_content}</td>
        </tr>
        `
        $('#viewAnnounce-table').append(tr)
      }
    },
  })
}

function closeFooterAnnounce() {
  //清除公告相关
  map.removeLayer(resultClipLayer)
  map.removeInteraction(drawLine)
  source.clear()
  map.on('click', addPopup)
  $('#footer-announce').addClass('hide')
}
